<template>
  <div class="waterfull-content grid">
    <!-- 瀑布流样式开始 -->
    <div class="waterfull clearfloat" id="waterfull">
        <!--<li class="grid-item" v-for="(task,index) in taskList">-->
        <!--<div class="task-video" v-if="task.video" v-html="task.video"></div>-->
        <!--<a href="javascript:void(0);" class="a-img" v-else-if="task.img">-->
        <!--<img :src="task.img" alt="" :title="task.title">-->
        <!--</a>-->
        <!--<h2 class="li-title" :title="task.title">{{task.title}}</h2>-->
        <!--<p class="description" :title="task.desc">{{task.desc}}</p>-->
        <!--<div class="qianm clearfloat" v-if="task.money">-->
        <!--<span class="sp1"><b>{{task.money ? '￥' + task.money : ''}}</b></span>-->
        <!--<p class="clearfloat good-and-look" v-if="false">-->
        <!--<span class="good"><i class="icon-zan iconfont"></i>200</span>-->
        <!--<span class="look"><i class="icon-Artboard iconfont"></i>688</span>-->
        <!--</p>-->
        <!--<img v-if="false" src="../../../static/z39pc/images/avatar.png" class="sp2" alt="" />-->
        <!--<span v-if="false" class="sp3">志强不息</span>-->
        <!--</div>-->
        <!--</li>-->
        <!--<li is="subMasonry" v-for="task in AlltaskList" v-bind:task="task" v-bind:key="task.id"  v-once></li>-->
      <subMasonryCom :taskList="AlltaskList"></subMasonryCom>
    </div>
    <!-- loading按钮自己通过样式调整 -->
    <div id="imloading"
         style="width:150px;height:30px;line-height:30px;font-size:16px;text-align:center;border-radius:3px;opacity:0.7;background:#000;margin:10px auto 30px;color:#fff;display:none">
      加载中...
    </div>
  </div>
</template>

<!--<script src="../../../static/z39pc/js/jquery.masonry.min.js" type="text/javascript" charset="utf-8"></script>-->
<script>
  import '../../../static/z39pc/js/jquery-2.1.0.js'
  import '../../../static/z39pc/js/jquery.masonry.min.js'
  import '../../../static/z39pc/js/jQeasing.js'
  import _ from 'underscore';
  import subMasonryCom from './subMasonry.vue';

  function loadImage(url) {
    var img = new Image();
    //创建一个Image对象，实现图片的预下载
    img.src = url;
    if (img.complete) {
      return img.src;
    }

    img.onload = function () {
      return img.src;
    };
  }

  function renderTasks(_this, container, loading, sqlJson) {
    console.log(sqlJson);
    sqlJson && (_this.AlltaskList = Object.assign([], [...sqlJson, ..._this.AlltaskList]));
    // console.log(_this.AlltaskList, 'xxxx');
    // if(sqlJson.length == 0) {
    // 	//loading.text('加载中...');
    // } else {
    // 	var html = "";
    // 	for(var i in sqlJson) {
    // 		html += "<li class='grid-item'>";
    //
    // 		if (sqlJson[i].video) {
    // 			html += '<div class="task-video">' + sqlJson[i].video + '</div>';
    // 		} else if (sqlJson[i].img) {
    // 			html += `<a href='javascript:void(0)' class='a-img'><img src="${sqlJson[i].img}"></a>`;
    // 		}
    // 		html += `<h2 class='li-title' >${sqlJson[i].title}</h2>`;
    // 		html += `<p class='description'>${sqlJson[i].desc}</p><div class='qianm clearfloat'>`;
    // 		var showBelow = sqlJson[i].money;
    // 		if (showBelow) {
    // 			html += `<span class="sp1"><b>￥ ${sqlJson[i].money}</b></span></div>`;
    // 					/**
    // 					<p class="clearfloat good-and-look">
    // 						<span class="good"><i class="icon-zan iconfont"></i>200</span>
    // 						<span class="look"><i class="icon-Artboard iconfont"></i>688</span>
    // 					</p>
    // 					<img src="./static/z39pc/images/avatar.png" class="sp2" alt="" />
    // 					<span class="sp3">志强不息</span>
    // 				</div>`**/
    // 		} else {
    // 			//html += `<div class="qianm clearfloat"><span class="sp1"><b></b></span></div>`;
    // 		}
    // }

    /*模拟ajax请求数据时延时800毫秒*/
    // var time = setTimeout(function() {
    // 	$(html).find('img').each(function(index) {
    // 		loadImage($(this).attr('src'));
    // 	});
    //
    // 	var $newElems = $(html).css({
    // 		opacity: 0
    // 	}).appendTo(container);
    //
    // 	$newElems.imagesLoaded(function() {
    // 		$newElems.animate({
    // 			opacity: 1
    // 		}, 800);
    // 		container.masonry('appended', $newElems, true);
    // 		loading.data("on", true).fadeOut();
    // 		clearTimeout(time);
    // 	});
    // }, 800);
  }


  function getContainerHeight(container, columns) {
    var items = container.find('.grid-item')
    var itemNum = items.length;
    if (items == null || itemNum == 0) {
      return 0;
    }

    var itemArr = [];
    var L = Math.min(columns, itemNum);
    for (var i = 0; i < L; i++) {
      var item = items.eq(itemNum - i);
      if (item.length && item.length == 1) {
        var itemH = item.offset().top + item[0].offsetHeight;
        itemArr.push(itemH);
      }
    }

    var maxTop = Math.max.apply(null, itemArr);
    return maxTop;
  }

  function getNextTasks(moreTasks, showNum) {
    var imgrule = /\!\[.{0,}\]\((.*\.(png|jpg|jpeg)(\?.+)?)\)/;
    var videorule = /\s*```video\s*(<video [^`]+<\/video>)/m;
    var L = Math.min(moreTasks.length, showNum);
    for (var i = 0; i < Math.min(moreTasks.length, L); i++) {
      if (moreTasks[i].desc) {
        var match = moreTasks[i].desc.match(videorule);
        if (match) {
          moreTasks[i].video = match[1];
          //moreTasks[i].desc = moreTasks[i].desc.replace(match[1], "");
        }
        match = moreTasks[i].desc.match(imgrule);
        if (match) {
          moreTasks[i].img = match[1];
        }
        moreTasks[i].desc = _.escape(moreTasks[i].desc);
      } else {
        moreTasks.splice(i, 1);
        i--;
      }
    }
    var showTasks = moreTasks.splice(0, showNum);
    return showTasks;
  }

  var oldTasks = null;

  export default {
    name: 'masonry',
    props: ['taskList', 'moreTaskList', 'qparams'],
    components: {
      subMasonryCom
    },
    data() {
      return {
        currentIndex: 0,
        AlltaskList: [],
      };
    },
    methods: {
      initMasonry: function () {
        console.log("initMasonry");
        var container = $('.waterfull ul');
        container.empty();
        var loading = $('#imloading');
        // 初始化loading状态
        loading.data("on", true).fadeOut();
        /*判断瀑布流最大布局宽度，最大为1280*/
        var tmpWid = $(window).width();
        var columns = Math.floor(tmpWid / 320);
        console.log("columns=", columns);

        function tores() {
          tmpWid = $(window).width();
          columns = Math.floor(tmpWid / 320);
          tmpWid = columns * 320;
          $('.waterfull').width(tmpWid);
        }

        tores();
        $(window).resize(function () {
          tores();
        });
        // container.imagesLoaded(function () {
        //   container.masonry({
        //     columnWidth: 960,
        //     itemSelector: '.grid-item',
        //     isFitWidth: true, //是否根据浏览器窗口大小自动适应默认false
        //     isAnimated: true, //是否采用jquery动画进行重拍版
        //     isRTL: false, //设置布局的排列方式，即：定位砖块时，是从左向右排列还是从右向左排列。默认值为false，即从左向右
        //     isResizable: true, //是否自动布局默认true
        //     animationOptions: {
        //       duration: 800,
        //       easing: 'easeInOutBack', //如果你引用了jQeasing这里就可以添加对应的动态动画效果，如果没引用删除这行，默认是匀速变化
        //       queue: false //是否队列，从一点填充瀑布流
        //     }
        //   });
        // });

        var that = this;
        var showTasks = [];
        var isFirst = false;
        if (true || that.taskList !== oldTasks) {
          isFirst = true;
          console.log(that.taskList);
          renderTasks(that, container, loading, that.taskList);
          var maxT = 5;
          var T = setInterval(function () {
            var ct = getContainerHeight($('.waterfull ul'), columns);
            console.log("ct=" + ct + ",sh=" + screen.height);
            if (maxT-- <= 0) {
              clearInterval(T);
            }
            if (ct < screen.height) {
              loading.data("on", true).fadeOut(800);
              var tasks = getNextTasks(that.moreTaskList, columns);
              renderTasks(that, container, loading, tasks);
            } else {
              clearInterval(T);
            }

          }, 2000);
          oldTasks = that.taskList;
        }

        /*本应该通过ajax从后台请求过来类似sqljson的数据然后，便利，进行填充，这里我们用sqlJson来模拟一下数据*/
        $(window).scroll(function () {
          console.log("scroll");
          if (!loading.data("on")) return;
          // 计算所有瀑布流块中距离顶部最大，进而在滚动条滚动时，来进行ajax请求，方法很多这里只列举最简单一种，最易理解一种
          var maxTop = getContainerHeight($('.waterfull ul'), columns);
          console.log("maxTop=" + maxTop);
          if (maxTop < $(window).height() + $(document).scrollTop()) {
            //加载更多数据
            loading.data("on", false).fadeIn(800);
            showTasks = getNextTasks(that.moreTaskList, columns * 2);
            console.log('进来之后等待渲染');
            renderTasks($(that, '.waterfull ul'), loading, showTasks);
          }
        });
      }
    },
    watchers: {},
    updated() {
      if (this.taskList !== oldTasks) {
        this.initMasonry();
      }
      console.log("updated");
    },
    mounted() {
      loadImage('./static/z39pc/images/masonry/one.jpeg');
      var that = this;

      this.initMasonry();
    }
  };
</script>

<style>
  /*.waterfull ul li .description {*/
    /*text-overflow: ellipsis;*/
    /*text-align: left;*/
    /*border-bottom: none;*/
  /*}*/

  /*.waterfull ul li .li-title {*/
    /*text-align: left;*/
    /*text-overflow: ellipsis;*/
    /*white-space: nowrap;*/
  /*}*/

  /*.task-video {*/
    /*width: 284px;*/
    /*height: 200px;*/
  /*}*/

  /*.task-video .video-js {*/
    /*width: 100%;*/
    /*height: 100%;*/
  /*}*/
</style>
